﻿using System;
using System.Collections.Generic;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Daemon.UsageChecking;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
using Sapphire.RSharp.Common;

namespace Sapphire.RSharp
{
  public class TroubleAnalyzer : ITroubleAnalyzer
  {
    private readonly CollectUsagesStageProcess _usagesProcess;
    private readonly IList<IElement> _watched;

    public TroubleAnalyzer(CollectUsagesStageProcess usagesProcess)
    {
      _usagesProcess = usagesProcess;
      _watched = new List<IElement>();
    }

    public IRecursiveElementProcessor Finder
    {
      get
      {
        return
          new TroubleAnalyzerProcessor(
            element =>
            {
              if (element is ICreationExpression)
              {
                var notInUsing = !(element as ICreationExpression).InUsing();

                if (notInUsing)
                  _watched.Add(element);
              }
            }
            );
      }
    }

    public IRecursiveElementProcessor Resolver
    {
      get
      {
        return new RecursiveElementProcessor(

          element =>
          {
            if (element is IDeclaredElement)
            {
              var usages = _usagesProcess.GetDeclaredElementUsages(element as IDeclaredElement);
              var disposed = usages.IsDisposed();

              if (disposed)
                _watched.RemoveChild(element);
            }
          });
      }
    }

    public IList<IElement> Watched
    {
      get { return _watched; }
    }

    public IHighlighting Highlighting
    {
      get { return new Rule01Highlighting(); }
    }
  }
}